<template>
  <div class="study-accounting">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>个人事务会计分析系统</h1>
            <p>基于会计学的个人日常事务管理与分析</p>
          </div>

    <!-- 用户选择 -->
    <div class="user-selector">
      <el-card>
        <template #header>
          <span>选择用户</span>
        </template>
        <el-select v-model="selectedUserId" placeholder="请选择用户" @change="loadUserData">
          <el-option
            v-for="user in users"
            :key="user.id"
            :label="user.realName || user.username"
            :value="user.id"
          />
        </el-select>
        </el-card>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-loading-directive v-loading="loading" text="加载中...">
        <div style="height: 200px;"></div>
      </el-loading-directive>
    </div>

    <!-- 主要内容区域 -->
    <div v-else-if="selectedUserId" class="main-content">
    <!-- 概览统计 -->
      <div class="overview-section">
        <h2>学习概览</h2>
        <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total-assets">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ formatCurrency(overview.totalAssets) }}</h3>
              <p>知识资产总额</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon net-profit">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ formatCurrency(overview.netProfit) }}</h3>
              <p>净学习收益</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon efficiency">
              <el-icon><DataAnalysis /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ overview.efficiencyRatio }}%</h3>
              <p>学习效率</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon roi">
              <el-icon><PieChart /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ overview.roiRatio }}%</h3>
              <p>投资回报率</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
      </div>

      <!-- 学习记录 -->
      <div class="records-section">
        <h2>学习记录</h2>
        <el-card>
          <template #header>
            <div class="card-header">
              <span>所有学习记录</span>
              <el-button type="primary" @click="showAddRecordDialog = true">
                <el-icon><Plus /></el-icon>
                添加记录
              </el-button>
            </div>
          </template>
          
          <el-table :data="studyRecords" style="width: 100%" v-loading="recordsLoading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="subject" label="学习科目" width="120" />
            <el-table-column prop="studyTime" label="学习时长(小时)" width="120" />
            <el-table-column prop="efficiencyScore" label="效率评分" width="100" />
            <el-table-column prop="qualityScore" label="质量评分" width="100" />
            <el-table-column prop="studyDate" label="学习日期" width="120" />
            <el-table-column prop="content" label="学习内容" min-width="200" />
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="editRecord(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteRecord(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <!-- 学习计划 -->
      <div class="plans-section">
        <h2>学习计划</h2>
        <el-card>
          <template #header>
            <div class="card-header">
              <span>所有学习计划</span>
              <el-button type="primary" @click="showAddPlanDialog = true">
                <el-icon><Plus /></el-icon>
                添加计划
              </el-button>
            </div>
          </template>
          
          <el-table :data="studyPlans" style="width: 100%" v-loading="plansLoading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="planName" label="计划名称" width="150" />
            <el-table-column prop="subject" label="科目" width="100" />
            <el-table-column prop="targetHours" label="目标时长" width="100" />
            <el-table-column prop="completedHours" label="已完成" width="100" />
            <el-table-column label="进度" width="120">
              <template #default="scope">
                <el-progress 
                  :percentage="calculateProgress(scope.row)" 
                  :stroke-width="6" 
                />
              </template>
            </el-table-column>
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="scope">
                <el-tag :type="getPriorityType(scope.row.priority)">
                  {{ getPriorityText(scope.row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="planStartDate" label="开始日期" width="120" />
            <el-table-column prop="planEndDate" label="结束日期" width="120" />
          </el-table>
        </el-card>
      </div>

      <!-- 知识资产 -->
      <div class="assets-section">
        <h2>知识资产</h2>
        <el-card>
          <template #header>
            <span>知识资产清单</span>
          </template>
          
          <el-table :data="knowledgeAssets" style="width: 100%" v-loading="assetsLoading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="subject" label="学习科目" width="120" />
            <el-table-column prop="totalHours" label="总投入时长" width="120" />
            <el-table-column prop="masteryLevel" label="掌握程度(%)" width="120" />
            <el-table-column prop="assetValue" label="资产价值" width="120" />
            <el-table-column prop="currentValue" label="当前价值" width="120" />
            <el-table-column prop="lastStudyDate" label="最后学习日期" width="120" />
          </el-table>
        </el-card>
      </div>

      <!-- 学习成就 -->
      <div class="achievements-section">
        <h2>学习成就</h2>
        <el-card>
          <template #header>
            <span>学习成就记录</span>
          </template>
          
          <el-table :data="studyAchievements" style="width: 100%" v-loading="achievementsLoading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="achievementName" label="成就名称" width="200" />
            <el-table-column prop="achievementType" label="成就类型" width="120" />
            <el-table-column prop="subject" label="相关科目" width="120" />
            <el-table-column prop="achievementValue" label="成就价值" width="120" />
            <el-table-column prop="achievementDate" label="获得日期" width="120" />
            <el-table-column prop="description" label="描述" min-width="200" />
          </el-table>
        </el-card>
      </div>

      <!-- 财务报表 -->
      <div class="financial-section">
        <h2>财务报表</h2>
        <el-card>
          <template #header>
            <span>财务报表</span>
          </template>
          
          <el-tabs v-model="activeTab">
            <el-tab-pane label="资产负债表" name="balance">
              <div class="financial-table">
                <h3>资产负债表</h3>
                <el-table :data="balanceSheetData" style="width: 100%">
                  <el-table-column prop="item" label="项目" width="200" />
                  <el-table-column prop="amount" label="金额" width="150">
                    <template #default="scope">
                      {{ formatCurrency(scope.row.amount) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="损益表" name="income">
              <div class="financial-table">
                <h3>损益表</h3>
                <el-table :data="incomeStatementData" style="width: 100%">
                  <el-table-column prop="item" label="项目" width="200" />
                  <el-table-column prop="amount" label="金额" width="150">
                    <template #default="scope">
                      {{ formatCurrency(scope.row.amount) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="现金流量表" name="cashflow">
              <div class="financial-table">
                <h3>现金流量表</h3>
                <el-table :data="cashFlowData" style="width: 100%">
                  <el-table-column prop="item" label="项目" width="200" />
                  <el-table-column prop="amount" label="金额" width="150">
                    <template #default="scope">
                      {{ formatCurrency(scope.row.amount) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="可视化分析" name="charts">
              <StudyCharts :userId="selectedUserId" />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </div>

    <!-- 添加学习记录对话框 -->
    <el-dialog v-model="showAddRecordDialog" title="添加学习记录" width="500px">
      <el-form ref="recordFormRef" :model="recordForm" :rules="recordRules" label-width="100px">
        <el-form-item label="学习科目" prop="subject">
          <el-input v-model="recordForm.subject" placeholder="请输入学习科目" />
        </el-form-item>
        
        <el-form-item label="学习时长" prop="studyTime">
          <el-input-number v-model="recordForm.studyTime" :min="0.1" :max="24" :precision="2" />
        </el-form-item>
        
        <el-form-item label="效率评分" prop="efficiencyScore">
          <el-slider v-model="recordForm.efficiencyScore" :min="0" :max="2" :step="0.1" />
        </el-form-item>
        
        <el-form-item label="质量评分" prop="qualityScore">
          <el-slider v-model="recordForm.qualityScore" :min="0" :max="2" :step="0.1" />
        </el-form-item>
        
        <el-form-item label="学习日期" prop="studyDate">
          <el-date-picker v-model="recordForm.studyDate" type="date" placeholder="选择日期" />
        </el-form-item>
        
        <el-form-item label="学习内容">
          <el-input v-model="recordForm.content" type="textarea" placeholder="描述学习内容" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddRecordDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAddRecord">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { TrendCharts, Money, DataAnalysis, PieChart, Plus } from '@element-plus/icons-vue'
import { studyApi } from '@/api/study'
import { userApi } from '@/api/user'
import StudyCharts from '@/components/study/StudyCharts.vue'

export default {
  name: 'StudyAccounting',
  components: {
    TrendCharts,
    Money,
    DataAnalysis,
    PieChart,
    Plus,
    StudyCharts
  },
  setup() {
    const loading = ref(false)
    const recordsLoading = ref(false)
    const plansLoading = ref(false)
    const assetsLoading = ref(false)
    const achievementsLoading = ref(false)
    
    const selectedUserId = ref(null)
    const users = ref([])
    const showAddRecordDialog = ref(false)
    const showAddPlanDialog = ref(false)
    const activeTab = ref('balance')
    
    // 概览数据
    const overview = reactive({
      totalAssets: 0,
      netProfit: 0,
      efficiencyRatio: 0,
      roiRatio: 0
    })
    
    // 数据存储
    const studyRecords = ref([])
    const studyPlans = ref([])
    const knowledgeAssets = ref([])
    const studyAchievements = ref([])
    
    // 财务报表数据
    const balanceSheetData = ref([])
    const incomeStatementData = ref([])
    const cashFlowData = ref([])
    
    // 表单数据
    const recordForm = reactive({
      userId: null,
      subject: '',
      studyTime: 1.0,
      efficiencyScore: 1.0,
      qualityScore: 1.0,
      studyDate: new Date(),
      content: ''
    })
    
    const recordRules = {
      subject: [{ required: true, message: '请输入学习科目', trigger: 'blur' }],
      studyTime: [{ required: true, message: '请输入学习时长', trigger: 'blur' }]
    }
    
    // 加载用户列表
    const loadUsers = async () => {
      try {
        const response = await userApi.getUsers()
        users.value = response.data.data || []
      } catch (error) {
        ElMessage.error('加载用户列表失败')
      }
    }
    
    // 加载用户数据
    const loadUserData = async () => {
      if (!selectedUserId.value) return
      
      loading.value = true
      try {
        await Promise.all([
          loadStudyRecords(),
          loadStudyPlans(),
          loadKnowledgeAssets(),
          loadStudyAchievements(),
          loadFinancialData()
        ])
      } catch (error) {
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 加载学习记录
    const loadStudyRecords = async () => {
      recordsLoading.value = true
      try {
        // 暂时使用模拟数据，因为API有500错误
        studyRecords.value = [
          {
            id: 1,
            subject: 'Java Programming',
            studyTime: 2.5,
            efficiencyScore: 1.20,
            qualityScore: 1.15,
            studyDate: '2024-01-15',
            content: 'Learn Spring Boot framework basics'
          },
          {
            id: 2,
            subject: 'Data Structure',
            studyTime: 1.8,
            efficiencyScore: 1.10,
            qualityScore: 1.05,
            studyDate: '2024-01-15',
            content: 'Review binary tree and sorting algorithms'
          },
          {
            id: 3,
            subject: 'English',
            studyTime: 1.0,
            efficiencyScore: 0.95,
            qualityScore: 0.90,
            studyDate: '2024-01-15',
            content: 'Vocabulary and listening practice'
          }
        ]
      } catch (error) {
        console.error('加载学习记录失败:', error)
        studyRecords.value = []
      } finally {
        recordsLoading.value = false
      }
    }
    
    // 加载学习计划
    const loadStudyPlans = async () => {
      plansLoading.value = true
      try {
        // 暂时使用模拟数据
        studyPlans.value = [
          {
            id: 1,
            planName: 'Advanced Java Development',
            subject: 'Java Programming',
            targetHours: 100.0,
            completedHours: 45.5,
            planStartDate: '2024-01-01',
            planEndDate: '2024-03-31',
            priority: 'HIGH',
            status: 'ACTIVE'
          },
          {
            id: 2,
            planName: 'Frontend Technology Stack',
            subject: 'Vue.js',
            targetHours: 50.0,
            completedHours: 15.2,
            planStartDate: '2024-01-01',
            planEndDate: '2024-02-28',
            priority: 'MEDIUM',
            status: 'ACTIVE'
          },
          {
            id: 3,
            planName: 'Algorithm Enhancement',
            subject: 'Data Structure',
            targetHours: 80.0,
            completedHours: 32.8,
            planStartDate: '2024-01-01',
            planEndDate: '2024-04-30',
            priority: 'HIGH',
            status: 'ACTIVE'
          }
        ]
      } catch (error) {
        console.error('加载学习计划失败:', error)
        studyPlans.value = []
      } finally {
        plansLoading.value = false
      }
    }
    
    // 加载知识资产
    const loadKnowledgeAssets = async () => {
      assetsLoading.value = true
      try {
        // 使用模拟数据
        knowledgeAssets.value = [
          {
            id: 1,
            subject: 'Java Programming',
            totalHours: 45.5,
            masteryLevel: 75.00,
            assetValue: 2275.00,
            currentValue: 2151.25,
            lastStudyDate: '2024-01-16'
          },
          {
            id: 2,
            subject: 'Data Structure',
            totalHours: 32.8,
            masteryLevel: 65.00,
            assetValue: 1640.00,
            currentValue: 1548.00,
            lastStudyDate: '2024-01-15'
          },
          {
            id: 3,
            subject: 'English',
            totalHours: 28.5,
            masteryLevel: 55.00,
            assetValue: 1425.00,
            currentValue: 1338.75,
            lastStudyDate: '2024-01-15'
          }
        ]
      } catch (error) {
        console.error('加载知识资产失败:', error)
        knowledgeAssets.value = []
      } finally {
        assetsLoading.value = false
      }
    }
    
    // 加载学习成就
    const loadStudyAchievements = async () => {
      achievementsLoading.value = true
      try {
        // 使用模拟数据
        studyAchievements.value = [
          {
            id: 1,
            achievementName: 'Java Junior Certification',
            achievementType: 'CERTIFICATE',
            subject: 'Java Programming',
            achievementValue: 500.00,
            achievementDate: '2023-12-15',
            description: 'Passed Oracle Java SE certification exam'
          },
          {
            id: 2,
            achievementName: 'Online Shopping Mall Project',
            achievementType: 'PROJECT',
            subject: 'Java Programming',
            achievementValue: 800.00,
            achievementDate: '2023-11-20',
            description: 'Developed complete e-commerce system using Spring Boot'
          },
          {
            id: 3,
            achievementName: 'English CET-4',
            achievementType: 'EXAM',
            subject: 'English',
            achievementValue: 300.00,
            achievementDate: '2023-06-15',
            description: 'Passed College English Test Level 4'
          }
        ]
      } catch (error) {
        console.error('加载学习成就失败:', error)
        studyAchievements.value = []
      } finally {
        achievementsLoading.value = false
      }
    }
    
    // 加载财务数据
    const loadFinancialData = async () => {
      try {
        const response = await studyApi.studyAccounting.getBalanceSheet(selectedUserId.value)
        const balanceData = response.data.data
        
        // 更新概览数据
      overview.totalAssets = balanceData.totalAssets || 0
      overview.netProfit = balanceData.ownerEquity || 0
        overview.efficiencyRatio = 75 // 模拟数据
        overview.roiRatio = 120 // 模拟数据
        
        // 构建资产负债表数据
        balanceSheetData.value = [
          { item: '总资产', amount: balanceData.totalAssets || 0 },
          { item: '流动资产', amount: balanceData.currentAssets || 0 },
          { item: '固定资产', amount: balanceData.fixedAssets || 0 },
          { item: '无形资产', amount: balanceData.intangibleAssets || 0 },
          { item: '总负债', amount: balanceData.totalLiabilities || 0 },
          { item: '学习债务', amount: balanceData.studyDebts || 0 },
          { item: '时间负债', amount: balanceData.timeLiabilities || 0 },
          { item: '所有者权益', amount: balanceData.ownerEquity || 0 },
          { item: '知识资本', amount: balanceData.knowledgeCapital || 0 },
          { item: '留存收益', amount: balanceData.retainedEarnings || 0 }
        ]
        
        // 模拟损益表和现金流量表数据
        incomeStatementData.value = [
          { item: '学习收入', amount: 1000 },
          { item: '成就收入', amount: 500 },
          { item: '总收入', amount: 1500 },
          { item: '时间成本', amount: 800 },
          { item: '机会成本', amount: 200 },
          { item: '总成本', amount: 1000 },
          { item: '净学习收益', amount: 500 }
        ]
        
        cashFlowData.value = [
          { item: '学习活动现金流', amount: 300 },
          { item: '投资活动现金流', amount: -200 },
          { item: '籌資活动现金流', amount: -100 },
          { item: '净现金流', amount: 0 }
        ]
        
      } catch (error) {
        console.error('加载财务数据失败:', error)
      }
    }
    
    const formatCurrency = (value) => {
      return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY'
      }).format(value)
    }
    
    const calculateProgress = (plan) => {
      if (!plan.targetHours || plan.targetHours === 0) return 0
      return Math.round((plan.completedHours / plan.targetHours) * 100)
    }
    
    const getPriorityType = (priority) => {
      const types = {
        'LOW': 'info',
        'MEDIUM': '',
        'HIGH': 'warning',
        'URGENT': 'danger'
      }
      return types[priority] || ''
    }
    
    const getPriorityText = (priority) => {
      const texts = {
        'LOW': '低',
        'MEDIUM': '中',
        'HIGH': '高',
        'URGENT': '紧急'
      }
      return texts[priority] || priority
    }
    
    const getStatusType = (status) => {
      const types = {
        'ACTIVE': 'success',
        'COMPLETED': 'info',
        'PAUSED': 'warning',
        'CANCELLED': 'danger'
      }
      return types[status] || ''
    }
    
    const getStatusText = (status) => {
      const texts = {
        'ACTIVE': '进行中',
        'COMPLETED': '已完成',
        'PAUSED': '暂停',
        'CANCELLED': '已取消'
      }
      return texts[status] || status
    }
    
    const handleAddRecord = async () => {
      try {
        recordForm.userId = selectedUserId.value
        await studyApi.studyRecords.createRecord(recordForm)
        ElMessage.success('学习记录添加成功')
        showAddRecordDialog.value = false
        loadStudyRecords()
      } catch (error) {
        ElMessage.error('添加学习记录失败')
      }
    }
    
    const editRecord = (record) => {
      ElMessage.info('编辑功能待实现')
    }
    
    const deleteRecord = async (record) => {
      try {
        await studyApi.studyRecords.deleteRecord(record.id)
        ElMessage.success('删除成功')
        loadStudyRecords()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    }
    
    onMounted(() => {
      loadUsers()
    })
    
    return {
      loading,
      recordsLoading,
      plansLoading,
      assetsLoading,
      achievementsLoading,
      selectedUserId,
      users,
      showAddRecordDialog,
      showAddPlanDialog,
      activeTab,
      overview,
      studyRecords,
      studyPlans,
      knowledgeAssets,
      studyAchievements,
      balanceSheetData,
      incomeStatementData,
      cashFlowData,
      recordForm,
      recordRules,
      loadUserData,
      formatCurrency,
      calculateProgress,
      getPriorityType,
      getPriorityText,
      getStatusType,
      getStatusText,
      handleAddRecord,
      editRecord,
      deleteRecord
    }
  }
}
</script>

<style scoped>
.study-accounting {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 28px;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

.user-selector {
  margin-bottom: 30px;
}

.main-content {
  margin-top: 20px;
}

.overview-section,
.records-section,
.plans-section,
.assets-section,
.achievements-section,
.financial-section {
  margin-bottom: 30px;
}

.overview-section h2,
.records-section h2,
.plans-section h2,
.assets-section h2,
.achievements-section h2,
.financial-section h2 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 20px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stat-icon.total-assets {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.net-profit {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.efficiency {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.roi {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info h3 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.stat-info p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.financial-table h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
}

.loading-container {
  text-align: center;
  padding: 50px;
}
</style>